package com.unipay.msm.controller;

import com.alibaba.excel.util.StringUtils;
import com.unipay.common.result.Result;
import com.unipay.msm.service.MsmService;
import com.unipay.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Project: yitong_parent
 * @Author: C.yu
 * @Time: 2023-05-04 20:42:42
 * @Desc: TODO
 */
@Api(tags = "短信验证接口")
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
    @Autowired
    private MsmService msmService;
    // redis操作类
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 通过手机号phone，发送短信验证码
    @GetMapping("send/{phone}")
    public Result send(@PathVariable String phone){
        //（1）从redis获取验证码code，获取成功：返回OK（code？？？）
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return Result.ok(code);
        }
        //（2）获取失败：通过短信API生成验证码，并-----保存到redis，设置有效时间等
        code = RandomUtil.getSixBitRandom();
        //TODO 调用service方法，通过整合短信服务进行发送
        boolean isSend = msmService.send(phone, code);
        System.out.println("isSend: " + isSend);
        if (isSend){
            redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
            return Result.ok(phone + ": " + code);
        }else {
            return Result.fail().message("短信发送失败！！！");
        }
    }
}
